package com.hxd.mall.network.base

import com.hxd.mall.R
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_10000
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_400
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_403
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_404
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_405
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_413
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_414
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_415
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_433
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_500
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_501
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_503
import com.hxd.mall.constant.HxdConstantsNet.Http_Code_9003
import com.hxd.mall.constant.HxdConstantsRouterPath.PathAccount.path_login_input_phone
import com.hxd.mall.constant.HxdGlobalInfo
import com.hxd.mall.module.account.login.LoginActivity
import com.hxd.mall.utils.local.ActivityUtil
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.StackManageUtil.currentActivity
import com.hxd.mall.utils.open.FaskClickUitl
import com.hxd.mall.utils.open.GsonUtil
import com.hxd.mall.utils.open.ToastUtil
import com.hxd.mall.utils.open.disssDialog
import com.orhanobut.logger.Logger
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import retrofit2.HttpException

/**
 * 网络接口回调，错误处理
 * Created by qishuai on 2018/7/27.
 */
abstract class BaseObserver<T> : Observer<T> {

    override fun onSubscribe(d: Disposable) {
    }

    override fun onNext(value: T) {
        try {
            val successBean = value as BaseBean
            if (successBean.code != 0 ) {
                if (successBean.code==9008){
                    //todo 临时修改 后期优化
                    onHandleSuccess(value)
                    return
                }
                onHandleError(successBean)
                // 令牌失效处理
                if (successBean.code == Http_Code_9003) {
                    // 多次打开Login
                    gotoLoginActivity()
                }
                return
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        //老街口数据转换异常 走成功标识
        onHandleSuccess(value)
    }

    override fun onError(e: Throwable) {
        var responseCode = Http_Code_10000
        if (e is HttpException) {
            responseCode = e.code()
        } else {
            onHandleError(BaseBean(responseCode, HxdGlobalInfo.instance.getString(R.string.data_error_tip)))
            return
        }
        // http响应码处理
        val msg = when (responseCode) {
            Http_Code_400 -> "请求服务器方式或语法错误"
            // 令牌失效处理
            Http_Code_9003 -> "当前账号已失效，请重新登录"
            Http_Code_403 -> "当前请求已被服务器拒绝"
            Http_Code_404 -> "未找到请求的服务地址"
            Http_Code_405 -> "请求的服务地址已被禁用"
            Http_Code_413,
            Http_Code_414 -> "请求服务时上传的验证数据或URL过长"
            Http_Code_415 -> "服务器接口暂不支持该类型的数据格式"
            Http_Code_500 -> "服务器处理异常，请稍后重试"
            Http_Code_501 -> "服务器无法识别该请求，请稍后重试"
            Http_Code_503 -> "服务器当前不可用，请稍后重试"
            else -> HxdGlobalInfo.instance.getString(R.string.net_error_tip)
        }

        // 令牌失效处理
        if (responseCode == Http_Code_9003) {
            // 多次打开Login
            gotoLoginActivity()
            return
        }
        //签约时风控没过返回
        if (responseCode == Http_Code_433) {
//            onHandleError(BaseErrorBean(code = Http_Code_433))
            onHandleError(BaseBean())
            return
        }
        try {
            val bodyJson = e.response().errorBody()!!.string()
            try {
                val baseErrorEntity = GsonUtil.json2bean(bodyJson, BaseBean::class.java)
                // 一般错误对象回调˙
                onHandleError(baseErrorEntity)
            } catch (e: Exception) {
                if (bodyJson.contains("<html>")) {
                    //onHandleError(BaseErrorBean(msg, ArrayList(), Http_Code_10000))
                    onHandleError(BaseBean(responseCode, msg))
                } else {
                    //onHandleError(BaseErrorBean(bodyJson, ArrayList(), Http_Code_10000))
                    onHandleError(BaseBean(responseCode, bodyJson))
                }
            }
        } catch (exception: Exception) {
            Logger.e("net error = ${exception.message}")
            //onHandleError(BaseErrorBean(msg, ArrayList(), Http_Code_10000))
            onHandleError(BaseBean(responseCode, msg))
        }
    }

    //跳转到登陆页面（如果是登陆界面 则停留在当前页面）
    private fun gotoLoginActivity() {
        if (FaskClickUitl.isFastClickFor401()) {
            return
        }
        if (currentActivity() != null && currentActivity()!!::class.java == LoginActivity::class.java) {
            return
        }
        ActivityUtil.clearUserInfo()
//        onHandleError(BaseBean(Http_Code_9003, ""))
        routerNavigation(path_login_input_phone)
        //因为mainActivity界面时没有关闭的 首页弹窗需要关闭
        disssDialog()
        //closeOtherOnlyActivity(MainActivity(), path_hxd_main_page)
//        closeOtherOnlyActivity(LoginActivity(), path_login_input_phone)

        ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_force_login))
    }

    override fun onComplete() {

    }

    protected abstract fun onHandleSuccess(t: T)

    protected abstract fun onHandleError(errorEntity: BaseBean)
}
